package com.zpark.merchant.app.intercept;

import com.zpark.jushanpay.common.domain.BusinessException;
import com.zpark.jushanpay.common.domain.CommonErrorCode;
import com.zpark.jushanpay.common.domain.ErrorCode;
import com.zpark.jushanpay.common.domain.RestErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局统一异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 定义处理异常的方法
    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processException(HttpServletRequest request,
                                              HttpServletResponse response, Exception e){

        //如果是自定义异常则直接取出异常信息
        if (e instanceof BusinessException) {
            LOGGER.info(e.getMessage(), e);
            BusinessException businessException = (BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            return new RestErrorResponse(String.valueOf(errorCode.getCode()), errorCode.getDesc());
        }

        LOGGER.error("系统异常：", e);
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKOWN.getCode()), CommonErrorCode.UNKOWN.getDesc());
    }
}
